package com.dawnClass.queueListener;


import com.rabbitmq.client.Channel;
import com.dawnClass.config.RabbitMQConfiguration;
import com.dawnClass.mapper.ConsumerOrderMapper;
import com.dawnClass.pojo.ConsumerOrder;
import com.dawnClass.pojo.ConsumerOrderExample;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class OrderInvalidationListener {
    @Autowired
    private ConsumerOrderMapper consumerOrderMapper;

    @RabbitListener(queues = RabbitMQConfiguration.deadQueueOrder)
    public void process(Channel channel, @Payload Message message , String orderNum) throws IOException {

//        final byte[] bytes = message.getBody();
        final MessageProperties messageProperties = message.getMessageProperties();
        final long deliveryTag = messageProperties.getDeliveryTag();

        //获取死信队列中达到失效时间的订单编号
        System.out.println("执行私信消费" + orderNum);
        //判断订单是否已经支付，如果支付则；否则，取消订单（逻辑代码省略)
        ConsumerOrderExample orderExample = new ConsumerOrderExample();
        orderExample.createCriteria().andOrderNumEqualTo(orderNum);
        ConsumerOrder order = consumerOrderMapper.selectByExample(orderExample).get(0);
        //（0删除，1失效，2未支付，3已完成，4拼团失败，5拼团中，6拼团成功）

        if (order.getOrdPayState() == 3) {
            //订单已支付，直接消费
            System.out.println("order：" + orderNum + "已支付");
            channel.basicAck(deliveryTag, false);
            return;
        }
        if (order.getOrdPayState() == 2) {
            //订单未支付，先修改订单状态再消费
            order.setOrdPayState(1);
            int rows = consumerOrderMapper.updateByPrimaryKey(order);
            if (rows > 0) {
                System.out.println("order：" + orderNum + "已失效");
            } else {
                System.out.println("order：" + orderNum + "订单状态修改失败，消息抛出");
                channel.basicNack(deliveryTag, false, false);
            }
        }
    }
}
